public without sharing class MeasureCalcFillController {

	public Boolean isErr {get;set;}

	public Boolean isSuccess {get;set;}

	public String msg {get;set;}

	public String paramJson {get;set;}
    public String calcJson {get;set;}//计算结果 

	public String regentJson {get;set;}//试剂结果

    public String adServiceJson {get;set;}//增值服务结果

	public String resJson {get;set;}//仪器结果

	public String searchJson {get;set;}//检索用的参数

	public String parentId {get;set;}//体系客户ID

	public String accId {get;set;}//客户ID 

	public Boolean isSys {get;set;}//是否为三方体系
    public Boolean isBM {get;set;}//是否为大家体系

	public String pname {get;set;}//产品名称

	public String pserialNo {get;set;}//产品货号

	public String pnccode {get;set;}//产品存货编码

	public String pspec {get;set;}//规格

	public String pmodel {get;set;}//型号

	public String pbrand {get;set;}//品牌

	public String pcategory1 {get;set;}//产品一级分类

	public String pcategory0 {get;set;}//产品主分类

	public String productType {get;set;}//产品类型

    public String papplication ;
    public String aplicableInstrumentcombbox {get;private set;}

	public String lastMothOpt {get;set;}//判断 > < = no  上月平均价

	public Boolean isNew ;//是新建还是编辑

	public String company {get;set;}//公司

	public String dataOpts {get;private set;}//选项

	public String backId {get;set;}//返回的Id 

	public String mcId {get;set;}//报价ID

	public String oppId {get;set;}///业务机会ID

	public Measure_Calculate__c mc {get;set;}//报价

	public Opportunity opp  {get;set;}//报价

	public String sealflag ;

	public String salescode {get;set;}
    public String province  {get;private set;}

	public String companycode;


	public String coopTypeJson {get;set;}//合作模式下拉框

	public String nowEstiJson {get;set;}//类型下拉框

    public String addtionServiceJson {get;set;}//类型下拉框


    ///public Boolean isNeedSelectAccount {get;private set;}//合作经销商是否必填

    public Boolean isCanEditCost {get;private set;}//是否可以修改集团成本

    public Boolean isCanEditSubCost {get;private set;}//是否可以修改子公司成本

    public Boolean isSaler {get;private set;} //是否是销售员

    public List<AdditionalService__c> asList {get;set;}//增值服务

    public User u ;//当前操作用户


    public String lastMcId ;

    public Boolean isCouldFindOverseaProduct;


    public Boolean isNeedSelectAccount {get ;private set;} //是否需要选择 报价适用 的终端客户

    public String  accMapJson {get; private set;}

    public String selectedAccId {get; set;}

    public Boolean isThird {get;private set;}//是否为三方

    public boolean isDirectlySaler {get ;private set;} 
    
    public String appAccId {get; private set;}

    public Boolean isGPO {get;private set;}

    public String maccuraJson {get;private set;}

    public class ControllerException extends Exception {}

    public MeasureCalcFillController() {
        mc = new Measure_Calculate__c();


        backId =System.currentPageReference().getParameters().get('mid');

        asList = new List<AdditionalService__c>();

        opp = new Opportunity();
        adServiceJson = '[]';

        u = [select Id ,Name ,Profile.Name,SubCompany__c from User where Id=:UserInfo.getUserId()];

        isNew = false;
        isCouldFindOverseaProduct = false;
         maccuraJson = MaccuraBrandUtil.getMaccuraJson();


    }

   
    private void setErr(String message ){   
        isErr  =true;
        throw new ControllerException(message);

    }

    public void setApplicableCustomers(){
        appAccId = mc.ApplicableCustomers__c;
        System.debug('setApplicableCustomers==>'+ appAccId);
    }

    private void getIntentTerinalAccount(){
       Map<String,String> accMap = new Map<String,String>();

        for(IntentProduct__c ip : [select TerminalClient__c,TerminalClient__r.Name from IntentProduct__c where Opportunity__c =:mc.Opportunity__c and TerminalClient__c != null ]){

            accMap.put(ip.TerminalClient__r.Name,ip.TerminalClient__c );
        }
        accMapJson = JSON.serialize(accMap);

    }



    //初始化页面
    public void init(){

        if(u.Profile.Name.contains('海外'))isCouldFindOverseaProduct = true;
        isDirectlySaler  = u.Profile.Name == '销售部直销销售员';

        isSaler = u.Profile.Name == '销售部分销销售员' || u.Profile.Name == '销售部直销销售员';
        //isSaler = true;
        Boolean isSuperEdit =   u.Profile.Name == '系统管理员' || u.Profile.Name == '财务部总监' || u.Profile.Name == '财务部主管' ;
        try{
            if(backId == null )setErr('页面打开错误!');
            if(Id.valueOf(backId).getSObjecttype() == Measure_Calculate__c.SObjectType ){
                mcId = backId;
                mc = getMeasureCalc(backId);
                if(mc == null)setErr('页面打开错误!');
                oppId = mc.Opportunity__c;
                opp  = [select Id,StageName,Owner.PriceProvince__c,RecordType.DeveloperName,Account.Name,Account.System__c,Account.ParentId ,Account.Parent.AccountNumber ,  Account.Level__c ,Account.LISRevenue__c from Opportunity where Id=:oppId];
                if( mc.Status__c == '审批成功' || ( mc.Status__c == '已提交' && (!isSuperEdit &&  isSaler)) )setErr('已提交或审批成功不能修改!');

            }else if(Id.valueOf(backId).getSObjecttype() == Opportunity.SObjectType ){
                oppId = backId;
                //,ExecutiveCompany__c,ExecutiveCompany__r.Name, ExecutiveCompany__r.RecordType.DeveloperName,
                opp  = [select Id,StageName,RecordType.DeveloperName ,Owner.PriceProvince__c,Account.Parent.AccountNumber,Account.Name, Account.ParentId ,Account.Level__c ,Account.System__c, Account.LISRevenue__c from Opportunity where Id=:backId];
                if(opp == null)setErr('页面打开错误!');

                if(( opp.StageName == '合同签订'  || opp.StageName == '失败'))setErr('不能在业务机会的'+opp.StageName+'阶段新建测算!');
               //opp.RecordType.DeveloperName != 'DealerOpportunity' && 
                isNew = true;
                lastMcId = getLastMeasureCalc(backId);
                if(lastmcid != null){
                    mc = getMeasureCalc(lastMcId).clone();
                    mc.LastMeasureCalc__c = lastMcId;
                    mc.IsActive__c = false;
                }
                mc.Opportunity__c = opp.Id;
                mc.Company__c = [select Id,SubCompany__c from User where Id=:UserInfo.getUserId()].SubCompany__c;
                mc.Status__c = '草案中';
                mc.RecordTypeId = Utils.getRecordTypeIdByDevNameAndObjName('StandardCalculation', 'Measure_Calculate__c');

                mc.Id = null;



            }else {
                setErr('页面打开错误!');
            }
            province = opp.Owner.PriceProvince__c;

            isGPO = opp.Account.Parent.AccountNumber == '301133';
            parentId = opp.Account.ParentId;

            appAccId = opp.AccountId;
              //是否需要选择适用客户
            isNeedSelectAccount = (opp.RecordType.DeveloperName == 'DealerOpportunity') ? true  : false  ;
            isThird = opp.Account.System__c != null;
            isBM =opp.Account.ParentId != null &&  opp.Account.System__c == '大家检验';
            //设置终端客户
            if(!isNeedSelectAccount) mc.TerminalName__c = opp.AccountId ; 
            /*if(opp.ExecutiveCompany__c == null ){
                setErr('业务机会执行公司不能为空!');
            }*/

            //isNeedSelectAccount = opp.ExecutiveCompany__r.RecordType.DeveloperName == 'Maccura' ? false: true;
            company = mc.Company__c;

            isCanEditCost = editGroupCostRight();
            isCanEditSubCost = editCostRight();

            //isSaler = true;
            companycode = ImportObject.getPicklistValues('Contract__c','Corpcode__c',false).get(company);

            sealflag  =  'Y-'+ companycode;
            salescode = ImportObject.getPicklistValues('PriceList__c', 'SalesCode__c', false).get(company);
            coopTypeJson = getSelectOpts('Measure_Calculate_Product__c','CoopType__c');
            nowEstiJson = getSelectOpts('Measure_Calculate_Product__c','NowEsti__c');
            aplicableInstrumentcombbox = getOptMap(ImportObject.getPicklistValues('Product__c', 'ApplicableInstrumentModel__c', true));
            getDealer();
            getServiceOpts();
            getIntentTerinalAccount();
          

        }catch(Exception e ){
             ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));
             isErr = true;
        }
    	
    }
      public void getDealer(){

        if(isNeedSelectAccount){
            accId = opp.AccountId ;
            mc.CoopDealer__c = accId;
        }else{
            accId = opp.AccountId;
            mc.CoopDealer__c  = null;
        }
     
    }
     public String getOptMap(Map<String,String> opts){
       Map<String ,Object> cooMap = new Map<String ,Object> ();
      cooMap.put('valueField', 'value');
      cooMap.put('textField', 'label');
      cooMap.put('panelHeight', 'auto');
      cooMap.put('limitToList', 'true');
      List<Map<String,String>>  dList = new List<Map<String,String>>();
      for (String k : opts.keySet()) {
        Map<String ,String> dataMap = new Map<String,String>();
        dataMap.put('label',opts.get(k) );
        dataMap.put('value',k );
        dList.add(dataMap);
      }  
      cooMap.put('data', dList);   
      
      return EncodingUtil.urlEncode(JSON.serialize(cooMap), 'UTF-8');
    }
    ///获取增值服务
    private List<AditionalServiceBean> getService() {
        List<AditionalServiceBean> tmp   = new List<AditionalServiceBean>();
        if(mc.Id != null ){
             asList = [select Id, Name, Cost__c from AdditionalService__c where MeasureCalc__c = :mc.Id ];
            for (AdditionalService__c ass : [select Id, Name, Cost__c from AdditionalService__c where MeasureCalc__c = :mc.Id ]) {
                tmp.add(new AditionalServiceBean(ass));
            }

            //paramJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');
        }
        return tmp ;

    }
    public void getServiceOpts(){
        Map<String,String> adMap =ImportObject.getPicklistValues('Measure_Calculate__c', 'AdditionalService__c', false);
        List<AditionalServiceBean> tmp   = new List<AditionalServiceBean>();
        for (String k : adMap.keySet()) {
                tmp.add(new AditionalServiceBean(k));
        }
         addtionServiceJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');


    }
    ///获取下拉列表
    public String getSelectOpts(String objName ,String fieldName ){
    	Map<String ,Object> cooMap = new Map<String ,Object> ();
    	cooMap.put('valueField', 'value');
    	cooMap.put('textField', 'label');
    	cooMap.put('panelHeight', 'auto');
		cooMap.put('limitToList', 'true');
    	List<Map<String,String>>  dList = new List<Map<String,String>>();
    	Map<String,String >opts = ImportObject.getPicklistValues(objName, fieldName, false);
    	for (String k : opts.keySet()) {
    		Map<String ,String> dataMap = new Map<String,String>();
    		dataMap.put('label',opts.get(k) );
    		dataMap.put('value',k );
    		dList.add(dataMap);
    	}  
    	cooMap.put('data', dList);   
    	
    	return EncodingUtil.urlEncode(JSON.serialize(cooMap), 'UTF-8');

    }

    //获取上次测算的信息 如有审批通过的 则取审批通过的 没有审批通过的则 按时间取最新的
    public String getLastMeasureCalc(String opid){
        List<Measure_Calculate__c>  mList = new List<Measure_Calculate__c> ();
        mList = [select Id from  Measure_Calculate__c where Opportunity__c =:opid  and RecordType.DeveloperName !='SimpleCalculation' and Status__c = '审批成功' Order by  CreatedDate desc ];
        if(mList.size() > 0) return mList[0].Id;
       //mList = [select Id from  Measure_Calculate__c where Opportunity__c =:opid   Order by  CreatedDate desc ];
        //if(mList.size() > 0) return mList[0].Id;
        return null;
    }


    //获取测算信息
    public Measure_Calculate__c getMeasureCalc(String mid ){
    	 Schema.DescribeSobjectResult m = Measure_Calculate__c.sObjectType.getDescribe();
            Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

            String sql = 'select ';
            String fields = '';
            for (String field : fieldMap.keySet()) {
                if (fields.length() > 0) {
                    fields += ', '; 
                }
                fields += field;
            }
            sql += fields;
            sql += ',TerminalName__r.Name ,TerminalName__r.LISRevenue__c,TerminalName__r.Level__c,Opportunity__r.Account.Name,Opportunity__r.Account.Level__c,Opportunity__r.Account.LISRevenue__c,Opportunity__r.CoopDealer__r.Name,ApplicableCustomers__r.Name   ';
            sql += ' from Measure_Calculate__c where Id = \'' + mid + '\'';
           List<Measure_Calculate__c> mcList = Database.query(sql);
           if(mcList == null || mcList.size() == 0)return null;
           return mcList[0];

    }


    public void getDetails(){

        Map<String,Object> resMap = new Map<String,Object>();
        resMap.put('equip', getEquip());
        resMap.put('regent', getRegent());
        //resMap.put('intent', getEquipmentFromIntentProduct());
        resMap.put('service',getService());
        paramJson = EncodingUtil.urlEncode(JSON.serialize(resMap), 'UTF-8');

    }
    ///获取仪器
   private List<Measure_Calculate_ProductBean> getEquip(){
        List<Measure_Calculate_ProductBean> mpL= new List<Measure_Calculate_ProductBean>();
   		if(mcId != null ){
   			mpL = getEquipmentFromMeasure_Calculate(mcId,true);
   		}else if(lastMcId != null ){
           mpL = getEquipmentFromMeasure_Calculate(lastMcId,true);
        }
        return mpL;
   }
   //获取试剂
   private List<Measure_Calculate_ProductBean> getRegent(){
        List<Measure_Calculate_ProductBean> mpL= new List<Measure_Calculate_ProductBean>();
   		if(mcId != null){
   			mpL = getEquipmentFromMeasure_Calculate(mcId,false);
   		}else if(lastMcId != null ){
           mpL = getEquipmentFromMeasure_Calculate(lastMcId,false);
        }
         return mpL;
   }
   //从产品中选择
    public void getProduct(){


    	String sql = 'select Id,Name ,Unit__c,brand__c,Spec__c ,SerialNo__c ,Model__c ,NCCode__c,Category1__c,Category2__c,Category0__c,zl__c,SealCompany__c ,TypeName__c,swjhdj__c,TestNumber__c,MatchingInstrument__c,ApplicableInstrumentModel__c ';

    	 sql += ' from Product__c where  RecordType.DeveloperName = \'NCProduct\' and NCCode__c != null  and Category0__c not in '+Label.EuipmentCategory0+' and (PriceCompany__c like\'%'+companycode+'%\' or Company__c like \'%'+company+'%\' )  ';
        if(!isCouldFindOverseaProduct) sql += ' and Overseasproducts__c != true ';
        
        if(String.isBlank(pname) == false ) sql += ' and Name like \'%'+pname+'%\' ';
    	 if(String.isBlank(pbrand) == false ) sql += '  and Brand__c like \'%'+pbrand+'%\' ';
    	 if(String.isBlank(pspec) == false ) sql += '  and Spec__c like \'%'+pspec+'%\' ';
    	 if(String.isBlank(pnccode) == false ) sql += '  and NCCode__c like \'%'+pnccode+'%\' ';
    	 if(String.isBlank(pcategory0) == false ) sql += '  and Category0__c like \'%'+pcategory0+'%\' ';
    	 if(String.isBlank(pcategory1) == false ) sql += '  and Category1__c like \'%'+pcategory1+'%\' ';
    	 if(String.isBlank(pserialNo) == false ) sql += '  and SerialNo__c like \'%'+pserialNo+'%\' ';
    	 if(String.isBlank(productType) == false ) sql += '  and TypeName__c like \'%'+productType+'%\' ';
         if(String.isBlank(papplication) == false ) sql += '  and ApplicableInstrumentModel__c includes (\''+papplication+'\') ';

    	sql +=' limit 300 ';

    	List<Product__c>pList = Database.query(sql);
    	List<Measure_Calculate_ProductBean> tmp = new List<Measure_Calculate_ProductBean>();
    	if(pList == null || pList.size() == 0){
 	    	paramJson = EncodingUtil.urlEncode(JSON.serialize(tmp),	 'UTF-8');
    	 	return;
    	 }
    	Set<Id>  pids= new Set<Id>();
    	for(Product__c p :pList){
    		 if(!(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag)))pids.add(p.Id);
    	}
        Map<Id,Price__c> prMap  =  ImportObject.getPriceMap(pids,company,province);
     //    String companyName =  !isGPO&& isThird  ? '迈克生物股份有限公司':company;

    	// Map<Id,Price__c> prMap = !isGPO&& isThird ?ImportObject.getPriceMap(pids, companyName) : ImportObject.getPriceMap(pids, companyName,province);
        System.debug('-->'+accId+'pids'+pids+'-->'+salescode);
        Map<Id,PriceList__c> priceListMap = parentId == null ? ImportObject.getPriceListMap(pids, accId,appAccId,salescode,company,false) :ImportObject.getPriceListMap(pids, parentId,salescode,company,true) ;
    	//Map<Id,PriceList__c> priceListMap = ImportObject.getPriceListMap(pids, accId,appAccId, salescode, false);
        Map<Id,AveragePrice__c> lastMothMap = ImportObject.getLastMothPrice(pids, mc.Company__c,province);
    	for(Product__c p :pList){
            ///如果产品品牌为迈克 没有价格体系则 排除掉
    	    //if(p.Brand__c != null && p.Brand__c.contains('迈克') && priceListMap.get(p.Id) == null ) continue;
            //isNeedSelectAccount
             if(!(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag))){
                tmp.add(new Measure_Calculate_ProductBean(p,prMap.get(p.Id),lastMothMap.get(p.Id),priceListMap.get(p.Id),companycode,isGPO,isBM ));
             }
    		

    	}
    	
    	paramJson = EncodingUtil.urlEncode(JSON.serialize(tmp),	 'UTF-8');

    }    //从测算产品中带入测算产品 
    private List<Measure_Calculate_ProductBean> getEquipmentFromMeasure_Calculate(String mid,Boolean isEquip ){

        Schema.DescribeSobjectResult m = Measure_Calculate_Product__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

        String sql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        sql += fields;
        sql += ' ,Product__r.Brand__c,Product__r.Unit__c,Product__r.Spec__c,Product__r.SerialNo__c,Product__r.Model__c ,Product__r.swjhdj__c,Product__r.MatchingInstrument__c,';
    	sql += ' Product__r.Category1__c,Product__r.Category2__c,Product__r.Category0__c,Product__r.zl__c,Product__r.NCCode__c,';
    	sql += ' Product__r.Name,Product__r.SealCompany__c ,Product__r.TypeName__c,Product__r.ApplicableInstrumentModel__c  ';
        sql += ' from Measure_Calculate_Product__c where Measure_Calculate__c = \'' + mid + '\' and IsEquipRelated__c =' + isEquip;
       List<Measure_Calculate_Product__c> temp = Database.query(sql);
       Set<Id>  pids= new Set<Id>();
       for ( Measure_Calculate_Product__c mcp : temp) {
           pids.add(mcp.Product__c);
       }
        Map<Id,Price__c> priceMap =  ImportObject.getPriceMap(pids,company,province);

      //   String companyName =  !isGPO&& isThird  ? '迈克生物股份有限公司':company;

     	// Map<Id,Price__c> priceMap = !isGPO&& isThird ? ImportObject.getPriceMap(pids,companyName) :  ImportObject.getPriceMap(pids,companyName,province);
        Map<Id,PriceList__c> priceListMap = parentId == null ? ImportObject.getPriceListMap(pids, accId,appAccId,salescode,company,false) :ImportObject.getPriceListMap(pids, parentId,salescode,company,true) ;
        Map<Id,AveragePrice__c> lastMothMap = ImportObject.getLastMothPrice(pids, company,province);

    	List<Measure_Calculate_ProductBean> tmpList = new List<Measure_Calculate_ProductBean>();
       for(Measure_Calculate_Product__c mcp : temp){
       		tmpList.add(new Measure_Calculate_ProductBean(mcp,priceMap.get(mcp.Product__c),lastMothMap.get(mcp.Product__c),priceListMap.get(mcp.Product__c),companycode,isEquip,isBM ));
       }

        // //明细数据之间建立 配置关系
        // for(ConfigurationListDetail__c cgl : [select Id,Configuration__c,InstrumentModel__c  from ConfigurationListDetail__c where   SoftWareKit__c = true and Configuration__c in:pids   ]){

        //   for (Measure_Calculate_ProductBean qt  : tmpList) {
        //     if(qt.productId == cgl.Configuration__c ){
        //       qt.relatedId = cgl.InstrumentModel__c;
        //       break;
        //     }
        //   }
        // }
       return tmpList;
      // paramJson = EncodingUtil.urlEncode(JSON.serialize(tmpList), 'UTF-8');


    }


     //从意向产品中带出仪器到测算
    public void  getEquipmentFromIntentProduct(){

        System.debug('MeasureCalcFillController==>'+selectedAccId);
        System.debug('MeasureCalcFillController==>'+isNeedSelectAccount);
        System.debug('MeasureCalcFillController==>'+mc);

        String terminalId = isNeedSelectAccount ?selectedAccId : mc.TerminalName__c ; 
        System.debug('MeasureCalcFillController==>'+terminalId);
        // 把仪器从意向产品带过来
       Schema.DescribeSobjectResult m = IntentProduct__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

        String sql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        sql += fields;
        sql += ' ,Product__r.Brand__c,Product__r.Unit__c,Product__r.Spec__c,Product__r.SerialNo__c,Product__r.Model__c ,Product__r.swjhdj__c,';
    	sql += 'Product__r.Category1__c,Product__r.Category2__c,Product__r.Category0__c,Product__r.zl__c,Product__r.NCCode__c,';
    	sql += 'Product__r.Name,Product__r.SealCompany__c ,Product__r.TypeName__c  ,Product__r.MatchingInstrument__c,Product__r.ApplicableInstrumentModel__c ';
        sql += ' from IntentProduct__c where Opportunity__c = \'' + oppId + '\'  and ( TerminalClient__c = \''+terminalId+'\' ) and ( Product__r.Category0__c  in  '+Label.EuipmentCategory0  +' ) ' ;
       
       System.debug('MeasureCalcFillController==>'+ sql);
       


       List<IntentProduct__c> ipList = Database.query(sql);
        Set<Id> pidset = new Set<Id>();
        Map<Id,Id> productTerminalMap = new Map<Id,Id>();
        for(IntentProduct__c ip : ipList){

            pidset.add(ip.Product__c);
            productTerminalMap.put(ip.Product__c, ip.TerminalClient__c);
        }

        String sql1 = ' select Id , Configuration__r.Brand__c,Configuration__r.Spec__c,Configuration__r.SerialNo__c,Configuration__r.Model__c ,Configuration__r.swjhdj__c,'+
         'Configuration__r.Category1__c,Configuration__r.Category2__c,Configuration__r.Category0__c,Configuration__r.zl__c,Configuration__r.NCCode__c,'+
        'Configuration__r.Name,Configuration__r.SealCompany__c ,Configuration__r.TypeName__c ,InstrumentModel__c ,Amount__c'+
         ' from ConfigurationListDetail__c where SoftWareKit__c = true and  InstrumentModel__c in (select Product__c from IntentProduct__c where Opportunity__c = \'' + oppId + '\'  and  ( TerminalClient__c = \''+terminalId+'\'  ) and  Product__r.Category0__c  in  '+Label.EuipmentCategory0  +'  ) ' ;
       List<ConfigurationListDetail__c> pList = Database.query(sql1);
       for(ConfigurationListDetail__c p : pList){

            pidset.add(p.Id);
        }

      
        Map<Id,Price__c> priceMap = new Map<Id,Price__c>();

        //String companyName =  !isGPO&& isThird  ? '迈克生物股份有限公司':company;

        //if(pidset.size()> 0)priceMap = !isGPO&& isThird  ? ImportObject.getPriceMap(pidset,  companyName) : ImportObject.getPriceMap(pidset,  companyName,province );
        priceMap = ImportObject.getPriceMap(pidset,  company,province );
        Map<Id,AveragePrice__c> lastMothMap = ImportObject.getLastMothPrice(pidset, company,province);

    	List<Measure_Calculate_ProductBean> tmpList = new List<Measure_Calculate_ProductBean>();
        Map<Id,Decimal> pNumMap = new Map<Id,Decimal>();
       // Set<Id> exset = new Set<Id>();
        //产品:终端map
        for(IntentProduct__c ip : ipList){
            pNumMap.put(ip.Product__c , ip.Quantity__c);
            //如果是配套 终端不一样则跳过
            if(productTerminalMap.containsKey(ip.Product__r.MatchingInstrument__c ) && productTerminalMap.get(ip.Product__r.MatchingInstrument__c) != ip.TerminalClient__c )continue;
            tmpList.add(new Measure_Calculate_ProductBean(ip,priceMap.get(ip.Product__c),lastMothMap.get(ip.Product__c),companycode));
           // exset.add(ip.Product__c );
        }

        for(ConfigurationListDetail__c p : pList){
            Measure_Calculate_ProductBean mcpb = new Measure_Calculate_ProductBean(p,priceMap.get(p.Configuration__c),lastMothMap.get(p.Configuration__c),companycode,pNumMap.get(p.InstrumentModel__c));
           if(!productTerminalMap.containsKey(p.Configuration__c  )   )  tmpList.add(mcpb);
          
            
            
        }



        System.debug('***'+tmpList);
         paramJson = EncodingUtil.urlEncode(JSON.serialize(tmpList), 'UTF-8');
       // return tmpList;
       

    }
      public void search(){
    	pname = '';
    	pbrand = '';
    	pspec = '';
    	pnccode = '';
    	pserialNo = '';
    	pcategory0 = '';
    	pcategory1 = '';
    	lastMothOpt = '';
    	productType = '';
        papplication = '';

    	System.debug('***'+searchJson); 
    	//System.debug('***'+EncodingUtil.urlDecode(searchJson, 'UTF-8')); 
    	Map<String,Object> searchMap =(Map<String,Object> )JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson, 'UTF-8'));
    	String type = String.valueOf(searchMap.get('type')) ;
    	String productName =  String.valueOf(searchMap.get('productName')) ;
		String brand =  String.valueOf(searchMap.get('brand')) ;
		String spec =  String.valueOf(searchMap.get('spec') );
		String cate0 =  String.valueOf(searchMap.get('cate0')) ;
		String nccode =  String.valueOf(searchMap.get('nccode')) ;
		String cate1=  String.valueOf(searchMap.get('cate1') );
		String serialNo=  String.valueOf(searchMap.get('serialNo') );
		 lastMothOpt=  String.valueOf(searchMap.get('lastMothOpt') );
		String ptype=  String.valueOf(searchMap.get('ptype') );


		if( productName != null && productName != '')pname = productName;
		if( brand != null && brand != '')pbrand = brand;
		if( spec != null && spec != '')pspec = spec;
		if( cate0 != null && cate0 != '')pcategory0 = cate0;
		if( cate1 != null && cate1 != '')pcategory1 = cate1;
		if( nccode != null && nccode != '')pnccode = nccode;
		if( serialNo != null && serialNo != '')pserialNo = serialNo;
		if( ptype != null && ptype != '')productType = ptype;
        if(String.isNotBlank(String.valueOf(searchMap.get('application')))) papplication = String.valueOf(searchMap.get('application'));


    	if(type == 'FromProduct'){//从产品中选择
    		getProduct();
        }
    	// }else if(type == 'ParentProduct'){//体系价目表中选择

    	// }else if(type == 'PriceProduct'){//从价目表中选择

    	// }else if(type == 'SelectEquipFromIntent'){
    	// 	//getEquipmentFromIntentProduct();
    	// }
    }

    ///保存
    public void save(){

        msg = '';
        System.debug('**'+resJson);
       

        SavePoint sp = Database.setSavepoint();
        try {
          
            if(isNew)mc.Id = null ;
           
            Map<String,Object> resMap =  ( Map<String,Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(calcJson, 'UTF-8')); 
            mc.MaccuraYieldNow__c = getDecimalValue(resMap.get('groupProfit'));
            mc.CompanyYieldNow__c = getDecimalValue(resMap.get('subProfit'));
            mc.MaccuraIncomeNow__c = getDecimalValue(resMap.get('groupIncome'));
            mc.CompanyIncomeNow__c = getDecimalValue(resMap.get('subIncome'));
            mc.MaccuraSalesNow__c = getDecimalValue(resMap.get('groupSale'));
            mc.CompanySalesNow__c = getDecimalValue(resMap.get('subSale'));
            System.debug('MaccuraYieldNo==>'+resMap);
            System.debug('MaccuraYieldNo==>'+mc);

            upsert mc;

            List<Measure_Calculate_Product__c> mcpList = new List<Measure_Calculate_Product__c>();
            mcpList.addALL(genMcpList(resJson,true));
            mcpList.addALL(genMcpList(regentJson,false));
            if(msg.length() > 0)return ;
            List<Measure_Calculate_Product__c> deleList =[select Id from Measure_Calculate_Product__c 
                where Measure_Calculate__c =:mc.Id ];
            if(deleList != null && deleList.size() > 0) delete deleList;

            System.debug(mcpList);
            insert mcpList;

            List<AdditionalService__c> asDelList = [select Id,Name,Cost__c from AdditionalService__c where MeasureCalc__c = :mc.Id];
            if (asDelList.size() > 0) delete asDelList;

            List<Object> resList=(List<Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(adServiceJson, 'UTF-8'));
            if(resList.size() > 0){
                List<AdditionalService__c> asInsList = new List<AdditionalService__c>();

                for (Object res : resList) {
                    Map<String ,Object> o = (Map<String ,Object> )res;
                    AdditionalService__c a =  new AdditionalService__c();
                    a.MeasureCalc__c = mc.Id;
                    if(o.get('name') != null ){
                        a.Name  = String.valueOf(o.get('name'));
                    }else{
                        continue;
                    }
                    if(o.get('cost') != null ){
                        a.Cost__c  = getDecimalValue(o.get('cost'));
                    }
                    asInsList.add(a);
                }
                   if(asInsList.size()>0) insert asInsList;

            }
            backId = mc.Id;
             mcId = mc.Id;
            isSuccess = true;
            msg = '保存成功!';

        }catch(Exception e){
            System.debug('异常'+e.getStackTraceString()+e.getMessage());
            Database.rollback(sp);
            msg = '保存失败:'+e.getMessage();
        }   

    }

    public List<Measure_Calculate_Product__c> genMcpList(String data,Boolean isEquip){

            List<Object> resList=(List<Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(data, 'UTF-8'));

            List<Measure_Calculate_Product__c> mcpList = new List<Measure_Calculate_Product__c>();
            if(resList.size() == 0){
                msg = isEquip ?  '保存失败,没有仪器数据!' :'保存失败,没有试剂数据!';
                return mcpList;
            }

        
           // Set<String> prosets = new Set<String>();
            for (Object res : resList) {
                Map<String ,Object> o = (Map<String ,Object> )res;
                Measure_Calculate_Product__c mcp  = new Measure_Calculate_Product__c();
                
                String productId = o.get('productId') == null ? null : String.valueOf(o.get('productId'));
                if(productId == null ){
                    msg = o.get('productName') +'的产品ID为空,不能保存!';
                    break;
                }else{
                    //prosets.add(productId);
                    mcp.Product__c = productId;
                }
                String relatedId = o.get('relatedId') == null ? null : String.valueOf(o.get('relatedId'));
                mcp.RelatedProduct__c = relatedId;
                mcp.IsEquipRelated__c = isEquip;
                mcp.Measure_Calculate__c = mc.Id;

                if(o.get('cate0') != null ){
                    mcp.Category0__c  = String.valueOf(o.get('cate0'));
                }
                if(o.get('cate1') != null ){
                    mcp.ProductLine__c  = String.valueOf(o.get('cate1'));
                }
                if(isEquip){

                   if(o.get('repairCost') != null ){
                        mcp.RepairCost__c  = getDecimalValue(o.get('repairCost'));
                    } 
                    if(o.get('coopType') != null ){
                        mcp.CoopType__c  = String.valueOf(o.get('coopType'));
                    }
                     if(o.get('quatity') != null ){
                        mcp.Quantity__c  = getDecimalValue(o.get('quatity'));
                    }
                    if(o.get('price') != null ){
                        mcp.SalesPriceWT__c  = getDecimalValue(o.get('price'));
                    }
                    if(o.get('isOut') != null )mcp.IsOutDoor__c = String.valueOf(o.get('isOut')) ;
                }else{
                     if(o.get('price') != null ){
                        mcp.SalesPriceWT__c  = getDecimalValue(o.get('price'));
                    }
                     if(o.get('marketPrice') != null ){
                        mcp.UnitPriceWT__c  = getDecimalValue(o.get('marketPrice'));
                    }

                    if(o.get('sampleNum1') != null ){
                        mcp.SampleNum1__c  = getDecimalValue(o.get('sampleNum1'));
                    }

                    if(o.get('testNum') != null ){
                        mcp.TestNum__c  = getDecimalValue(o.get('testNum'));
                    }

                   
                    if(o.get('taxrate') != null ){
                        mcp.TaxRate__c  =getDecimalValue(o.get('taxrate'));
                    }

                }
                
                if(o.get('companyBottomPrice') != null ){
                    mcp.CompanyBottomPrice__c  = getDecimalValue(o.get('companyBottomPrice'));
                }
                
                if(o.get('brand') != null ){
                    mcp.Brand__c  = String.valueOf(o.get('brand'));
                }

                /*if(o.get('dealerInstCost') != null ){
                    mcp.DealerInstCost__c  = getDecimalValue(o.get('dealerInstCost'));
                }*/
                if(o.get('subCost') != null ){
                    mcp.SubInstCost__c    = getDecimalValue(o.get('subCost'));
                }
                if(o.get('groupCost') != null ){
                    mcp.InstCost__c  =getDecimalValue(o.get('groupCost'));
                }
                if(o.get('gpoprice') != null ){
                    mcp.GPOPrice__c  =getDecimalValue(o.get('gpoprice'));
                }
                
               String brand = o.get('brand') != null ?String.valueOf(o.get('brand')) :'';
               // !brand.contains('迈克') 
                if( !MaccuraBrandUtil.maccura.contains(brand)){
                    mcp.InstCost__c = mcp.SubInstCost__c;
                }
                mcpList.add(mcp);

            }
            return mcpList;
    }
    

     private Decimal getDecimalValue(Object val){
        if(val == null)return null;
        String  d = String.valueOf(val);
        if(d == '')return null;
        return Decimal.valueOf(d.trim());
    }
    ///置空参数
    public void setNil(){
    	paramJson = '';
    	searchJson = '';
    	resJson = '[]';
    	pname = '';
    	pbrand = '';
    	pspec = '';
    	pnccode = '';
    	pcategory0 = '';
    	pcategory1 = '';
    	regentJson = '';
        adServiceJson = '[]';
        selectedAccId = '';
    }

     private Boolean editCostRight(){
          //子公司经理 财务经理 财务总监  销售中心总监
        if(( u.Profile.Name == '财务部总监' || u.Profile.Name =='销售中心总监' || u.Profile.Name == '系统管理员')||
            (u.Profile.Name == '财务部主管' && u.SubCompany__c == mc.Company__c)  || Label.MeasureChangeCost == u.Name  ){

            return true;
        }
        return false;
    }
    //集团成本修改权限
    private Boolean editGroupCostRight(){
        //销售中心总监 财务总监 西南区财务经理(云南 贵州 重庆 + 实业) 
        Set<String> companys= new Set<String>();
        companys.add('四川省迈克实业有限公司');
        companys.add('重庆征途科技有限公司');
        companys.add('云南迈克科技有限公司');
        companys.add('贵州迈克科技有限公司');
          //子公司经理 财务经理 财务总监  销售中心总监
        if(( u.Profile.Name == '财务部总监' || u.Profile.Name == '系统管理员')){

            return true;
        }else if(u.Profile.Name == '财务部主管' && u.SubCompany__c == mc.Company__c && companys.contains(u.SubCompany__c)){
            return true;
        }
        return false;

    }
     public class AditionalServiceBean{
        public String name ;
        public Decimal cost ;
        public AditionalServiceBean(AdditionalService__c ass){
            name  = ass.Name;
            cost = ass.Cost__c;
        }
        public AditionalServiceBean(String n){
            name  = n;
         
        }

     }
     public class Measure_Calculate_ProductBean{
     //	public String type {get;set;}//类型
     	public String productId {get;set;}//产品ID
    	public String productName {get;set;}//产品名称
    	public String brand {get;set;}//品牌
    	public String  spec {get;set;}//规格
    	public String  serialNo {get;set;}//货号
    	public String  model {get;set;}//型号
    	public String  nccode {get;set;}//存货编码
    	public String  productType {get;set;}//产品类型

    	public Decimal price {get;set;}//单价
        public Decimal originPrice {get;set;}//单价

    	public Decimal sysPrice {get;set;}//第三方体系价

    	public Decimal adprice {get;set;} //调整价格

    	public String cate0 {get;set;}//主分类
    	public String cate1 {get;set;}//一级分类
    	public String cate2 {get;set;}//二级分类
        public String unit ;
        public String application ;

    	public String zl  {get;set;}//装量

    	public Decimal taxrate {get;set;}//税率
    	public Decimal companyBottomPrice {get;set;}//公司底价
    	public Decimal areaDealerPrice {get;set;}//区域经销商价
    	public Decimal invoiceDealerPrice {get;set;}//报价经销商价
    	public Decimal hospitalManagerPrice {get;set;}//终端指导价
    	public Decimal marketPrice {get;set;}//市场报价
    	public Decimal lastMothPrice {get;set;}//上月平均价

    	public Decimal sampleNum1 {get;set;}//第一年标本量	

    	public Decimal instCost {get;set;}//成本价
        public Decimal subCost {get;set;}//子公司成本
        public Decimal groupCost {get;set;}//集团成本

    	/*public Decimal dealerInstCost {get;set;}//经销商成本价
       	public Decimal subInstCost {get;set;}// 子公司成本价*/
        public Decimal repairCost {get;set;}//维修成本



        public String coopType {get;set;}//合作模式
        public Decimal quatity {get;set;}//数量

        public Decimal testNum {get;set;}//测试数
        public Boolean isEqp {get;set;}//是不是仪器 
        public String relatedId {get;private set;}

        public Decimal gpoprice ; 

        public String isOut {get;private set;}

        public Boolean canChange {get; private set;}



        //仪器或者试剂
      	public  Measure_Calculate_ProductBean(Measure_Calculate_Product__c mp ,Price__c pr,AveragePrice__c ap ,PriceList__c pl ,String companycode,Boolean isEquip ,Boolean isBM){

      		quatity = mp.Quantity__c;
      		coopType = mp.CoopType__c;
      		productId = mp.Product__c;
    		productName = mp.Product__r.Name;
    		spec = mp.Product__r.Spec__c;
    		model = mp.Product__r.Model__c;
    		serialNo = mp.Product__r.SerialNo__c;
    		nccode = mp.Product__r.NCCode__c;
    		brand = mp.Product__r.Brand__c;
            relatedId = mp.RelatedProduct__c; 
    		cate0 = mp.Product__r.Category0__c;
    		cate1 = mp.Product__r.Category1__c;
    		cate2 = mp.Product__r.Category2__c;
            unit = mp.Product__r.Unit__c;

    		productType = mp.Product__r.TypeName__c;
            application = mp.Product__r.ApplicableInstrumentModel__c;
            canChange = (MaccuraBrandUtil.maccura.contains(mp.Product__r.NCCode__c) || MaccuraBrandUtil.maccura.contains(mp.Product__r.Brand__c) )&& isBM  ? false : true ;
    		price = mp.SalesPriceWT__c;
            
            originPrice = mp.SalesPriceWT__c;

    		coopType = mp.CoopType__c;
    		quatity = mp.Quantity__c;
    		sampleNum1 = mp.SampleNum1__c;
    		testNum = mp.TestNum__c ;
            isEqp = isEquip;
            isOut = mp.IsOutDoor__c; 

    		if(pr != null ){
    			companyBottomPrice = pr.CompanyBottomPrice__c;
    			areaDealerPrice = pr.AreaDealerPrice__c;
    			instCost = pr.InstCost__c;
    			invoiceDealerPrice = pr.InvoiceDealerPrice__c;
    			hospitalManagerPrice = pr.HospitalManagerPrice__c;
    			marketPrice = pr.MarketPrice__c;
    			repairCost = pr.RepairCost__c;

    		}
            lastMothPrice = ap == null ? 0 : ap.AveragePrice__c;
             taxrate  = mp.TaxRate__c == null ? ( pr == null?0:pr.Taxrate__c == null ?0:pr.Taxrate__c ) : mp.TaxRate__c;
            taxrate  = (taxrate == null || taxrate == 0 ) ? getTaxRate(companycode, brand) : taxrate ;

            if(isEqp){//如果是仪器

               // dealerInstCost = (mp.DealerInstCost__c == null || mp.DealerInstCost__c == 0 ) ? (pr != null ? pr.AreaDealerPrice__c : 0) : mp.DealerInstCost__c ;
                subCost = (mp.SubInstCost__c == null || mp.SubInstCost__c == 0) ?(  pr != null ? pr.InstCost__c : 0) :mp.SubInstCost__c;
               // groupCost  = (mp.InstCost__c == null || mp.InstCost__c == 0.0)  ?( pr != null ? pr.InstCost__c : 0):mp.InstCost__c ; mp.Product__r.Brand__c.contains('迈克')
                groupCost = (mp.InstCost__c == null || mp.InstCost__c == 0.0) ? (mp.Product__r.Brand__c != null && MaccuraBrandUtil.maccura.contains(mp.Product__r.Brand__c)  ) ? (mp.Product__r.swjhdj__c != null  ? mp.Product__r.swjhdj__c *(1+TaxRate/100.0):null ) : (pr == null ? 0 : pr.InstCost__c == null ? 0 :pr.InstCost__c   ) : mp.InstCost__c; 

            }else{//如果是试剂
                subCost = (mp.SubInstCost__c == null || mp.SubInstCost__c == 0) ?( pr == null ? 0 : pr.InstCost__c):mp.SubInstCost__c;
               // dealerInstCost = (mp.DealerInstCost__c == null || mp.DealerInstCost__c == 0 )?(pl == null?0:pl.Price__c):mp.DealerInstCost__c;  .contains('迈克')
                groupCost = (mp.InstCost__c == null || mp.InstCost__c == 0.0) ? (mp.Product__r.Brand__c != null && MaccuraBrandUtil.maccura.contains(mp.Product__r.Brand__c)) ? (mp.Product__r.swjhdj__c != null  ? mp.Product__r.swjhdj__c *(1+TaxRate/100.0):null ) : (pr == null ? 0 : pr.InstCost__c == null ? 0 :pr.InstCost__c   ) : mp.InstCost__c; 
            }

       	}
        //配套
         //仪器
        public  Measure_Calculate_ProductBean(ConfigurationListDetail__c mp ,Price__c pr ,AveragePrice__c ap ,String companycode,Decimal n  ){

           quatity = n* mp.Amount__c ;
           // price = mp.SalesPrice__c;
           // coopType =mp.CoopType__c;
            isEqp = true;
            productId = mp.Configuration__c ;
            productName = mp.Configuration__r.Name;
            spec = mp.Configuration__r.Spec__c;
            model = mp.Configuration__r.Model__c;
            serialNo = mp.Configuration__r.SerialNo__c;
            nccode = mp.Configuration__r.NCCode__c;
            brand = mp.Configuration__r.Brand__c;
            relatedId = mp.InstrumentModel__c; 
            canChange = true;

            cate0 = mp.Configuration__r.Category0__c;
            cate1 = mp.Configuration__r.Category1__c;
            cate2 = mp.Configuration__r.Category2__c;
            productType = mp.Configuration__r.TypeName__c;
            zl = mp.Configuration__r.zl__c;
            isOut = '出库';
            if(pr != null ){
                taxrate  = pr.Taxrate__c == null ? 0 :  pr.Taxrate__c ;
                companyBottomPrice = pr.CompanyBottomPrice__c;
                areaDealerPrice = pr.AreaDealerPrice__c;
                instCost = pr.InstCost__c;
                invoiceDealerPrice = pr.InvoiceDealerPrice__c;
                hospitalManagerPrice = pr.HospitalManagerPrice__c;
                marketPrice = pr.MarketPrice__c;
                repairCost = pr.RepairCost__c;
            }else{
                taxrate = 0;
            }
            taxrate  = (taxrate == null || taxrate == 0 ) ? getTaxRate(companycode, brand) : taxrate ;

            lastMothPrice = ap == null ? 0 : ap.AveragePrice__c;
            //price = mp.SalesPrice__c;

            /*
            mcp.InstCost__c = pr != null ? pr.InstCost__c : 0 ;//集团成本(价格 成本价)
            mcp.DealerInstCost__c = pr != null ? pr.AreaDealerPrice__c : 0;//经销商成本(价格 区域经销商价)
            mcp.SubInstCost__c = pr != null ? getSubCompanyPrice(com,pr) : 0;//子公司价（云南、贵州、重庆、四川-实业，生物 几个公司取价格体系中的成本价）
            mcp.RepairCost__c = pr != null ? Pr.RepairCost__c : 0 ;
            */
            /*
            mcp.InstCost__c =(p.InstCost__c == null  || p.InstCost__c== 0 )? pr != null ? pr.InstCost__c : 0:p.InstCost__c ;//集团成本(价格 成本价)
            mcp.DealerInstCost__c =(p.DealerInstCost__c == null || p.DealerInstCost__c == 0) ? pr != null ? pr.AreaDealerPrice__c : 0 :p.DealerInstCost__c;//经销商成本(价格 区域经销商价)
            mcp.SubInstCost__c = (p.SubInstCost__c == null || p.SubInstCost__c == 0) ? pr != null ? getSubCompanyPrice(com,pr) : 0 : P.SubInstCost__c;//子公司价（云南、贵州、重庆、四川-实业，生物 几个公司取价格体系中的成本价）
            mcp.RepairCost__c = (p.RepairCost__c == null || p.RepairCost__c == 0) ? pr != null ? pr.RepairCost__c : 0 : p.RepairCost__c;//报修成本
            */
           // dealerInstCost = pr != null ? pr.AreaDealerPrice__c : 0;
            subCost = pr != null ? pr.InstCost__c : 0;
           // groupCost  =  pr != null ? pr.InstCost__c : 0 ;
          
            groupCost = (mp.Configuration__r.Brand__c != null && MaccuraBrandUtil.maccura.contains(mp.Configuration__r.Brand__c) ) ? (mp.Configuration__r.swjhdj__c != null  ? mp.Configuration__r.swjhdj__c *(1+taxrate/100.0):null ) : (pr == null ? 0 : pr.InstCost__c );             
        }
        //仪器
      	public  Measure_Calculate_ProductBean(IntentProduct__c mp ,Price__c pr ,AveragePrice__c ap ,String companycode ){

      		quatity = mp.Quantity__c;
      		price = mp.SalesPrice__c;
      		coopType =mp.CoopType__c;
            isEqp = true;
      		productId = mp.Product__c;
    		productName = mp.Product__r.Name;
    		spec = mp.Product__r.Spec__c;
    		model = mp.Product__r.Model__c;
    		serialNo = mp.Product__r.SerialNo__c;
    		nccode = mp.Product__r.NCCode__c;
    		brand = mp.Product__r.Brand__c;
             unit = mp.Product__r.Unit__c;
            //relatedId = mp.Product__r.MatchingInstrument__c; 
            application = mp.Product__r.ApplicableInstrumentModel__c;

    		cate0 = mp.Product__r.Category0__c;
    		cate1 = mp.Product__r.Category1__c;
    		cate2 = mp.Product__r.Category2__c;
    		productType = mp.Product__r.TypeName__c;
    		zl = mp.Product__r.zl__c;
            isOut = '出库';
    		if(pr != null ){
    			taxrate  = pr.Taxrate__c == null ? 0 :  pr.Taxrate__c ;
    			companyBottomPrice = pr.CompanyBottomPrice__c;
    			areaDealerPrice = pr.AreaDealerPrice__c;
    			instCost = pr.InstCost__c;
    			invoiceDealerPrice = pr.InvoiceDealerPrice__c;
    			hospitalManagerPrice = pr.HospitalManagerPrice__c;
    			marketPrice = pr.MarketPrice__c;
    			repairCost = pr.RepairCost__c;
    		}else{
                taxrate = 0;
            }

            taxrate  = (taxrate == null || taxrate == 0 ) ? getTaxRate(companycode, brand) : taxrate ;

            lastMothPrice = ap == null ? 0 : ap.AveragePrice__c;
            //price = mp.SalesPrice__c;

            /*
            mcp.InstCost__c = pr != null ? pr.InstCost__c : 0 ;//集团成本(价格 成本价)
            mcp.DealerInstCost__c = pr != null ? pr.AreaDealerPrice__c : 0;//经销商成本(价格 区域经销商价)
            mcp.SubInstCost__c = pr != null ? getSubCompanyPrice(com,pr) : 0;//子公司价（云南、贵州、重庆、四川-实业，生物 几个公司取价格体系中的成本价）
            mcp.RepairCost__c = pr != null ? Pr.RepairCost__c : 0 ;
            */
            /*
            mcp.InstCost__c =(p.InstCost__c == null  || p.InstCost__c== 0 )? pr != null ? pr.InstCost__c : 0:p.InstCost__c ;//集团成本(价格 成本价)
            mcp.DealerInstCost__c =(p.DealerInstCost__c == null || p.DealerInstCost__c == 0) ? pr != null ? pr.AreaDealerPrice__c : 0 :p.DealerInstCost__c;//经销商成本(价格 区域经销商价)
            mcp.SubInstCost__c = (p.SubInstCost__c == null || p.SubInstCost__c == 0) ? pr != null ? getSubCompanyPrice(com,pr) : 0 : P.SubInstCost__c;//子公司价（云南、贵州、重庆、四川-实业，生物 几个公司取价格体系中的成本价）
            mcp.RepairCost__c = (p.RepairCost__c == null || p.RepairCost__c == 0) ? pr != null ? pr.RepairCost__c : 0 : p.RepairCost__c;//报修成本
            */
           // dealerInstCost = pr != null ? pr.AreaDealerPrice__c : 0;
            subCost = pr != null ? pr.InstCost__c : 0;
           // groupCost  =  pr != null ? pr.InstCost__c : 0 ;
          
            groupCost = (mp.Product__r.Brand__c != null && MaccuraBrandUtil.maccura.contains (mp.Product__r.Brand__c)) ? (mp.Product__r.swjhdj__c != null  ? mp.Product__r.swjhdj__c *(1+taxrate/100.0):null ) : (pr == null ? 0 : pr.InstCost__c );     		
      	}

        //试剂 ,Boolean isNeedSelectAccount
      	public  Measure_Calculate_ProductBean(Product__c p ,Price__c pr,AveragePrice__c ap ,PriceList__c pl ,String companycode ,Boolean isGPO,Boolean isBM ){

            canChange = (MaccuraBrandUtil.maccura.contains(p.NCCode__c) || MaccuraBrandUtil.maccura.contains(p.Brand__c) )&& isBM  ? false : true ;

      		productId = p.Id ;
    		productName = p.Name ;
    		spec = p.Spec__c;
    		model = p.Model__c;
    		serialNo = p.SerialNo__c;
    		nccode = p.NCCode__c;
    		brand = p.Brand__c;
    		cate0 = p.Category0__c;
    		cate1 = p.Category1__c;
    		cate2 = p.Category2__c;
             unit = p.Unit__c;
            //relatedId = p.MatchingInstrument__c; 
            application = p.ApplicableInstrumentModel__c;

            if(!isGPO && pl != null )price = pl.Price__c;

            if(pl != null )gpoprice = pl.Price__c;
             originPrice =price;


    		zl = p.zl__c;
    		productType = p.TypeName__c;
    		testNum = p.TestNumber__c;
    		//type = '现有';
            isEqp = false;
    		if(pr != null ){
    			//taxrate  = pr.Taxrate__c;
    			companyBottomPrice = pr.CompanyBottomPrice__c;
    			areaDealerPrice = pr.AreaDealerPrice__c;
    			instCost = pr.InstCost__c;
    			invoiceDealerPrice = pr.InvoiceDealerPrice__c;
    			hospitalManagerPrice = pr.HospitalManagerPrice__c;
    			marketPrice = pr.MarketPrice__c;
    			repairCost = pr.RepairCost__c;
    		}
            lastMothPrice = ap == null ? 0 : ap.AveragePrice__c;

            taxrate  = pr == null?0:pr.Taxrate__c == null ?0:pr.Taxrate__c ;

            taxrate  = (taxrate == null || taxrate == 0 ) ? getTaxRate(companycode, brand) : taxrate ;
    		subCost = pr == null ? 0 : pr.InstCost__c;


            groupCost = (p.Brand__c != null && MaccuraBrandUtil.maccura.contains(p.Brand__c)) ? (p.swjhdj__c != null  ? p.swjhdj__c *(1+taxrate/100.0):null ) : (pr == null ? 0 : pr.InstCost__c ); 
      	}

        private Decimal getTaxRate(String com,String brand ){
            Set<String> comset = new Set<String>{'MKSW','MKSY','CQZT','GDMK','SXMK'};
            if(comset.contains(com)) return (brand != null  && MaccuraBrandUtil.maccura.contains(brand))? 3.0 : 13.0 ;
            return 13.0 ;

        }


     }

}